const express = require("express");
const md5 = require("md5");
const handleDb = require("../db/handleDb");
require("colors");
router = express.Router();  // 页面路由

// 首页
router.get("/", (req, res) => {

    (async function index(){

        // 是否存在session
        let sessionId = await req.session["sessionId"];

        // 初始化数据
        let data = {userInfo: null, newList: [], rankList: [], category: []};

        // 如果sessionId存在，则从数据库中获取用户消息
        if(sessionId){
            let hasAccount = await handleDb(res, "info_user", "find", "查询账户失败", `id="${sessionId}"`);
            if(hasAccount.length > 0){
                let userInfo = hasAccount[0];
                data.userInfo = {
                    nick_name: userInfo.nick_name,
                    username: userInfo.username,
                    avatar_url: userInfo.avatar_url
                }
            }
        }

        // 查询新闻列表
        /* let hasAccount = await handleDb(res, "info_news", "find", "无新闻数据可查询"); */
        let newList = await handleDb(res, "info_news", "sql","数据查询失败", "select * from info_news order by create_time desc limit 10");
        data.newList = newList;

        // 按点击率查询新闻列表-只查询前6
        let rankList = await handleDb(res, "info_news", "sql","数据查询失败", "select * from info_news order by clicks desc limit 6");
        data.rankList = rankList;   // 排行榜列表

        // 头部分类标题
        let category = await handleDb(res, "info_category","find" ,"数据库查询失败");
        data.category = category;
        res.render("index", data);
    })();
});

// 账户登录
router.post("/login", (req, res) => {
    (async function login(){
        let username = await req.body.username;
        let password = await req.body.password;

        // 判断账户是否存在
        let hasAccount = await handleDb(res, "info_user", "find", "账户不存在", `username="${username}"`);

        if(hasAccount != null && hasAccount.length <= 0){
            res.json({errmsg: "账户未注册，请检查后重新登录!"});
            return;
        } else {
            let hasAccount = await handleDb(res, "info_user", "find", "账户不存在", `username="${username}" AND password_hash="${md5(password)}"`);
            if(hasAccount.length > 0){
                req.session["sessionId"] = hasAccount[0].id;

                // 更新最后登录时间
                // await handleDb(res, "info_user", "update","账户更新失败", `id=${hasAccount[0].id}`, {})


                res.json({
                    errno: "0",
                    errmsg: "登录成功!"
                });
            } else {
                res.json({errmsg: "账户未注册，请检查后重新登录!"});
            }
        } 
    })();
});

// 账户退出
router.get("/logout", (req, res) => {
    delete req.session["sessionId"];
    res.json({msg: "退出成功!"});
});


module.exports = router;